from socket import *

# Create a serSocket TCP connection

serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 12000

serverSocket.bind(('',serverPort))
serverSocket.listen(1)

while True:
    #
    print('Ready to serve...')

    # 1.建立传输数据的链接,服务端接收请求
    connectionSocket,addr = serverSocket.accept()

    # 获取数据
    try:

        #接收报文
        message = connectionSocket.recv(1024) 

        #将报文split 获取其中第二个元素作为文件名
        filename = message.split()[1]

        print(message)

        #如果获取的是/,则返回错误,因为需要一个具体的名称
        if filename =='/':
            raise IOError
        
        #open有什么用? 为什么filename要1:?????
        f = open(filename[1:]) 

        #获取从filename中获取的数据
        outputdata = f.read()

        #写HTTP响应报文 内容的长度与请求报文outputdata长度一致
        header = ' HTTP/1.1 200 OK\nConnection: close\nContent-Type :test/html\nContenet-Length: %d\n\n' %(len(outputdata))
        connectionSocket.send(header.encode())

        #发送报文后发送数据,把接收到的数据原样返回
        connectionSocket.send(outputdata.encode())

        connectionSocket.close()
    except IOError:
        # 如果对于无效请求报文
        header = ' HTTP/1.1 404 Not Found'
        connectionSocket.send(header.encode())
        connectionSocket.close()

